package ws

import (
	"GoServer/message"
	"GoServer/utils/debug"
	"encoding/json"
	"sync"
)

// 读写锁
var wsRWLocker sync.RWMutex

var messageTable map[uint64]func([]byte, string) = make(map[uint64]func([]byte, string), 0)

func RegisterWSHandler(id uint64, handler func([]byte, string)) {
	if _, exists := messageTable[id]; exists {
		debug.Logln(debug.Info, "消息ID %d 已存在，禁止重复注册", id)
		return
	}
	messageTable[id] = handler
}

func WSMessageCenter(data []byte, gameName string) {
	wsRWLocker.RLock()
	msg := message.Message{}
	err := json.Unmarshal(data, &msg)
	if err != nil {
		debug.Logln(debug.Error, err)
	} else {
		execute, ok := messageTable[msg.MsgType]
		if ok {
			execute(data, gameName)
		} else {
			/// 返回客户端消息错误
		}
	}

	wsRWLocker.RUnlock()
}
